<?php
use \GatewayWorker\Lib\Gateway;
class PM_v
{
    /*******************************************************************************************************************/
    public static function __checkRoomIsIn( $room_id , $client_id ,  $db_connect ){
        $room_info = PHZ_Room::__getRoomInfo_byID( $room_id , $db_connect);
        if( $room_info == false || $room_info == null || count( $room_info ) <= 0 ){
            if( Gateway::isOnline( $client_id ) == 1 ) {
                $data = array();
                $data['log_md']      = 33;
                $data['room_id']     = $room_id;
                $data['log_data']    = json_encode( array() );
                Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
            }
        }
        return true;
    }

    /*******************************************************************************************************************/
    public static function __UpdateRoom_ThisTimer( $room_id , $user_id , $db_connect ){
        $cols = array();
        $cols['this_timer'] = $user_id;
        return $db_connect->update('tt_room')->cols( $cols )->where('room_id=' . $room_id )->query();
    }

    /*******************************************************************************************************************/
    public static function __UserQuery_score( $user_id , $client_id , $db_connect ){
        $scoreField = PHZ_Member::__getFieldBy_ID( $user_id , "score" , $db_connect );
        //输出用户信息
        if( Gateway::isOnline( $client_id ) == 1 ) {
            $data = array();
            $data['log_md']      = 29;
            $data['score_info']  = $scoreField;
            $data['log_data']    = json_encode( array() );
            Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
        }
        return true;
    }

    /*******************************************************************************************************************/
    /**
     * 添加用户的不进入某房间的操作
     * @param $user_id
     * @param $room_id
     * @param $db_connect
     */
    public static function __UserFail_JoinRoom( $user_id , $room_id , $db_connect ){
        PHZ_Member::__UserFail_JoinRoom( $user_id , $room_id , $db_connect );
    }

    /*******************************************************************************************************************/
    /**
     * 用户修改音乐&音效，实时进行数据库记录操作
     * @param $user_id
     * @param $yy
     * @param $yx
     * @param $db_connect
     */
    public static function __UserUpdateConfig_YY_YX( $user_id , $yy , $yx , $db_connect ){
        $cols = array();
        $cols['config_yy'] = $yy;
        $cols['config_yx'] = $yx;
        return $db_connect->update('tt_member')->cols( $cols )->where('uid=' . $user_id )->query();
    }

    /*******************************************************************************************************************/
    /**
     * 用户修改背景图片，实时进行数据库记录操作
     * @param $user_id
     * @param $bg_name
     * @param $db_connect
     */
    public static function __UserUpdateConfig_BG( $user_id , $bg_name , $db_connect ){
        $cols = array();
        $cols['config_bg'] = $bg_name;
        return $db_connect->update('tt_member')->cols( $cols )->where('uid=' . $user_id )->query();
    }


    /*******************************************************************************************************************/

    /**
     * 通过用户ID查询他的详细信息，如果在房间内则计算相应的距离；通过client_id发送给用户
     * @param $user_id
     * @param $client_id
     * @param $db_connect
     */
    public static function __getUserINFO_AND_Distance( $room_id , $user_id , $client_id , $db_connect ){
        if( $room_id == "" ){return false;}
        //取出房间信息
        $room_info  = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        if( $room_info == false || $room_info == null || count( $room_info ) <= 0 ){return false;}
        //获取该用户的具体详情
        $member_info = PHZ_Member::__MemberISin_AND_getInfo( $user_id , $db_connect );
        if( $member_info == false ){
            return false;
        }
        //加入BUG修复：如果房间不是正在运行的状态，是不能发聊天消息的
        //加入BUG修复：准备房间跟正在进行的房间都允许查看个人信息框
        if( $room_info['room_status'] != 1 && $room_info['room_status'] != 0 ){
            return false;
        }
        //遍历房间里的每个人（除了自身外，计算与其他三个人的距离）
        $index = 1;$member_info[ "dis_1"] = $member_info[ "dis_2"] = $member_info[ "dis_3"] = "";//初始化三个人的距离信息
        foreach( $room_info as $key => $value ) {
            if (strstr($key, 'room_player_') != false && $value != 0 && $value != $user_id ) {
                $userInfo = PHZ_Member::__MemberISin_AND_getInfo( $value , $db_connect );
                if( $member_info['latitude'] == 0 || $member_info['longitude'] == 0 ){
                    $member_info["dis_" . $index] = "该用户(". urldecode($member_info['name']) .")尚未开启定位权限";
                }else {
                    if( $userInfo['latitude'] == 0 || $userInfo['longitude'] == 0 ){
                        $member_info["dis_" . $index] = "“" . urldecode($member_info['name']) . "” 距离 “" . urldecode($userInfo['name']) . "” " . "(未开启定位权限)";
                    }else {
                        $dis = self::__calDis($member_info['latitude'], $member_info['longitude'], $userInfo['latitude'], $userInfo['longitude'] , false );
                        $member_info["dis_" . $index] = "“" . urldecode($member_info['name']) . "” 距离 “" . urldecode($userInfo['name']) . "” " . $dis;
                    }
                }
                $index++;
            }
        }
        //进行用户信息的基础操作 -- 格式化score，判断level等级等
        $member_info['score']       = number_format( $member_info['score'] );
        $member_info['room_status'] = $room_info['room_status'];
        //输出用户信息
        if( Gateway::isOnline( $client_id ) == 1 ) {
            $data = array();
            $data['log_md']      = 27;
            $data['member_info'] = $member_info;
            $data['log_data']    = json_encode( array() );
            Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
        }
        return true;
    }

    /**
     * 通过经纬度计算玩家与玩家之间的距离
     * @param $lat1      查询者的纬度
     * @param $lng1      查询者的经度
     * @param $lat2      比较着的纬度
     * @param $lng2      比较者的经度
     * @param $is_meters 是否需要直接返回米数
     * @return bool|float|int
     */
    public static function __calDis( $lat1,  $lng1,  $lat2,  $lng2 , $is_meters = false ){
        $dis =  self::__GetDistance( $lat1,  $lng1,  $lat2,  $lng2 );
        if( $is_meters == false ) {
            if ($dis >= 3) {
                return $dis . "公里";
            } else {
                return ($dis * 1000) . "米";//换算成米（如果公里数小于等于3公里的时候，换算成米）
            }
        }else{
            return ($dis * 1000);
        }
    }
    public static function __rad( $number ){
        return $number * M_PI / 180.0;
    }
    public static function __GetDistance( $lat1,  $lng1,  $lat2,  $lng2 ){
        if( ( abs( $lat1 ) > 90  ) ||(  abs( $lat2 ) > 90 ) ){
            return false;
        }
        if( ( abs( $lng1 ) > 180  ) ||(  abs( $lng2 ) > 180 ) ){
            return false;
        }
        $radLat1 = self::__rad($lat1);
        $radLat2 = self::__rad($lat2);
        $a = $radLat1 - $radLat2;
        $b = self::__rad($lng1) - self::__rad($lng2);
        $s = 2 * asin( sqrt( pow( sin($a/2) , 2 ) + cos( $radLat1 ) * cos( $radLat2 ) * pow( sin($b/2) ,2)));
        $s = $s *6378.137 ;// EARTH_RADIUS;
        $s = round($s * 10000) / 10000;
        return $s;
    }
    /*******************************************************************************************************************/


    /**
     * 用户申请解散一个代开的房间
     * @param $room_id
     * @param $user_id
     * @param $client_id
     * @param $db_connect
     */
    public static function __UserApply_dissolutionGener_Room( $room_id ,  $user_id , $client_id , $db_connect ){
        //取出房间信息
        $room_info     = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        $status_string = "fail";
        //房间是否存在
        if( $room_info == null || $room_info == false ){
            $status_string = "room_nofail";//房间不存在
        }else{
            if( $room_info['room_cid'] != $user_id ){
                $status_string = "room_nofail";//解散者非开房者或房间已经开始游戏，错误同上
            }else{
                //是否已经存在用户，存在的情况下，不允许申请解散
                if( $room_info['room_player_1'] != 0 || $room_info['room_player_2'] != 0 || $room_info['room_player_3'] != 0 || $room_info['room_status'] != 0 ){
                    $status_string = "room_is_player";//房间内已经有玩家了，不能进行解散操作
                }else{
                    //删除整个room以及room对应的LOG信息
                    PHZ_Log::__DeleteRoom_ALLLOG( $room_id , $db_connect );
                    //删除整个room
                    PHZ_Room::__deleteRoom( $room_id , $db_connect );
                    //恢复用户的钻石(假如扣除了的话)
                    if( $room_info['consume'] >= 1 ){
                        PHZ_Member::__UserAdd_consume( $user_id , $room_info['consume'] , $db_connect );
                    }
                    //成功解散，更新房间缓存信息
                    PHZ_Memcache::__set_RoomInfo_ToMemcache( $room_info , true );
                    $status_string = "success";
                }
            }
        }
        //发送解散结果通知
        $data = array();
        $data['log_md']     = 995;//解散结果通知
        $data['log_status'] = $status_string;//索引需要重置（前端循环从0开始，导致匹配不到数据）
        Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
    }
    public static function __UserQuery_GenerHistory( $user_id , $client_id , $db_connect ){
        //取出所有该用户代开的房间，以0,1,2
        $where     = "room_cid = '". $user_id ."' AND is_daikai = 1";
        $room_list = $db_connect->select('*')->from('tt_room')->where( $where )->limit(10)->orderByDESC( array('room_time_micor') )->query();
        //进行一些信息的处理工作
        foreach ( $room_list  as $key => $value ){
            $room_list[$key]['room_time'] = date('m-d H:i' , $value['room_time_micor'] );//转化时间
            //获取用户名
            $room_list[$key]['p1_name'] = $value['room_player_1'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_1'] , "name" , $db_connect );
            $room_list[$key]['p2_name'] = $value['room_player_2'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_2'] , "name" , $db_connect );
            $room_list[$key]['p3_name'] = $value['room_player_3'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_3'] , "name" , $db_connect );
        }
        //输出回执
        $data = array();
        $data['log_md']   = 996;//ws中的回放对应
        $data['log_pl']   = 1;
        $data['log_data'] = array_values($room_list);//索引需要重置（前端循环从0开始，导致匹配不到数据）
        Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
    }

    /*******************************************************************************************************************/

    /**
     * 回放中心，用户近10间房的记录
     * @param $user_id
     * @param $client_id
     * @param $db_connect
     */
    public static function __BackUserROOM_List_Query( $user_id , $client_id , $db_connect ){
        //取出房间信息(近10间房,只要不是为1的，且不是为0的；都可以),不管是正常玩完还是解散
        $where   = "room_status = 2 AND room_player_1 = " . $user_id;
        $where  .= " or room_player_2 = " . $user_id;
        $where  .= " or room_player_3 = " . $user_id;
        $room_list = $db_connect->select('*')->from('tt_room')->where( $where )->limit(10)->orderByDESC( array('room_time_micor') )->query();
        //进行一些信息的处理工作
        foreach ( $room_list  as $key => $value ){
            $room_list[$key]['room_time'] = date('m-d H:i:s' , $value['room_time_micor'] );//转化事件
            foreach ( $value as $key_1 => $value_1 ){
                //获取输赢信息
                if (strstr($key_1, 'room_player_') != false && $value_1 == $user_id ) {
                    $user_score_key = 'player_'. str_replace("room_player_","",$key_1) .'_score';
                    if( $value[$user_score_key]  == 0 ){
                        $room_list[$key]['end'] = "flat";
                    }else if( $value[$user_score_key] < 0 ){
                        $room_list[$key]['end'] = "bad";
                    }else if( $value[$user_score_key] >= 1 ){
                        $room_list[$key]['end'] = "win";
                    }
                }
            }
            //获取用户名
            $room_list[$key]['p1_name'] = $value['room_player_1'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_1'] , "name" , $db_connect );
            $room_list[$key]['p2_name'] = $value['room_player_2'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_2'] , "name" , $db_connect );
            $room_list[$key]['p3_name'] = $value['room_player_3'] == 0 ? "" : PHZ_Member::__getFieldBy_ID( $value['room_player_3'] , "name" , $db_connect );
            //把每一期的结算信息都带上
            $room_list[$key]['scoring'] = $db_connect->select('*')->from('tt_room_scoring')->where( "room_id = " . $value['room_id'] )->orderByDESC( array('id') )->query();
            //如果没有结算数据，那么这期是无效的期数，（可能为提前解散了）
            if( count( $room_list[$key]['scoring'] ) >= 1 ){
                //遍历结算信息，把用户名带上
                foreach ( $room_list[$key]['scoring'] as $key_2 => $value_2 ){
                    $room_list[$key]['scoring'][$key_2]['p1_name'] = PHZ_Member::__getFieldBy_ID( $value_2['player_1'] , "name" , $db_connect );//用户名
                    $room_list[$key]['scoring'][$key_2]['p2_name'] = PHZ_Member::__getFieldBy_ID( $value_2['player_2'] , "name" , $db_connect );
                    $room_list[$key]['scoring'][$key_2]['p3_name'] = PHZ_Member::__getFieldBy_ID( $value_2['player_3'] , "name" , $db_connect );
                    if( $value_2['player_1'] == $user_id ){
                        $score = $value_2['player_1_score'];
                    }else if( $value_2['player_2'] == $user_id ){
                        $score = $value_2['player_2_score'];
                    }else if( $value_2['player_3'] == $user_id ){
                        $score = $value_2['player_3_score'];
                    }
                    if($score  == 0 ){
                        $room_list[$key]['scoring'][$key_2]['end'] = "flat";
                    }else if( $score < 0 ){
                        $room_list[$key]['scoring'][$key_2]['end'] = "bad";
                    }else if( $score >= 1 ){
                        $room_list[$key]['scoring'][$key_2]['end'] = "win";
                    }

                }
            }else{
                unset( $room_list[$key] );
            }
        }
        //输出回执
        $data = array();
        $data['log_md']   = 997;//ws中的回放对应
        $data['log_pl']   = 1;
        $data['log_data'] = array_values($room_list);//索引需要重置（前端循环从0开始，导致匹配不到数据）
        Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
    }

    /**
     * 回放中心，单局详情查询
     * @param $room_id
     * @param $room_js
     */
    public static function __BackINIT_DATA_QUERY( $room_id , $room_js , $user_id ,  $client_id , $db_connect ){
        //取出房间信息
        $room_info  = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        //取出所有该局的牌面信息
        $where     = "rid = '". $room_info['room_id'] ."' and jid = '". $room_js ."'";
        $card_info = $db_connect->select('*')->from('tt_room_card')->where( $where )->query();
        //取出用户顺序(我就是0)
        $shunxuArray = array();
        if( $room_info['room_player_1'] == $user_id ){
            $shunxuArray[$room_info['room_player_1']] = 0;
            $shunxuArray[$room_info['room_player_2']] = 1;
            $shunxuArray[$room_info['room_player_3']] = 2;
        }else if( $room_info['room_player_2'] == $user_id ){
            $shunxuArray[$room_info['room_player_1']] = 2;
            $shunxuArray[$room_info['room_player_2']] = 0;
            $shunxuArray[$room_info['room_player_3']] = 1;
        }else if( $room_info['room_player_3'] == $user_id ){
            $shunxuArray[$room_info['room_player_1']] = 1;
            $shunxuArray[$room_info['room_player_2']] = 2;
            $shunxuArray[$room_info['room_player_3']] = 0;
        }
        //用户数组
        $user_data = array();
        foreach ( $card_info as $key => $value ){
            $user_info     = PHZ_Member::__MemberISin_AND_getInfo( $value['uid'] , $db_connect );
            $i             = $shunxuArray[$value['uid']];//顺序
            $user_data[$i] = $value;
            $user_data[$i]['name'] = $user_info['name'];
            $user_data[$i]['uid']  = $value['uid'];
            $user_data[$i]['pai']  = PHZ_LiPai::__lipai( $value['init_sp'] , false , $room_info );
        }
        //输出回执
        $data = array();
        $data['log_md']   = 999;//ws中的回放对应
        $data['log_pl']   = 1;
        $data['log_data'] = $user_data;
        $data['room_id']  = $room_id;
        $data['room_js']  = $room_js;
        $data['play_data']= PHZ_Log::__getRoomJS_ALLDATA( $room_id , $room_js , $user_id , $db_connect );
        Gateway::sendToClient( $client_id , json_encode( $data ) ) ;
    }
}